package com.hhu.softpractise.controller;

import java.util.List;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhu.softpractise.annotation.AuthCheck;
import com.hhu.softpractise.common.BaseResponse;
import com.hhu.softpractise.common.DeleteRequest;
import com.hhu.softpractise.common.ErrorCode;
import com.hhu.softpractise.common.ResultUtils;
import com.hhu.softpractise.constant.UserConstant;
import com.hhu.softpractise.exception.BusinessException;
import com.hhu.softpractise.exception.ThrowUtils;
import com.hhu.softpractise.model.dto.post.*;
import com.hhu.softpractise.model.entiy.Post;
import com.hhu.softpractise.model.entiy.PostComment;
import com.hhu.softpractise.model.entiy.User;
import com.hhu.softpractise.model.vo.PostVO;
import com.hhu.softpractise.service.PostCommentService;
import com.hhu.softpractise.service.PostService;
import com.hhu.softpractise.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/post")
@Api( tags = "帖子接口")
public class PostController {

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Resource
    private PostCommentService postCommentService;



    /**
     * 创建
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @ApiOperation( value = "创建帖子")
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(postAddRequest == null, ErrorCode.PARAMS_ERROR);
        //将postAddRequest复制给post
        Post post = new Post();
        BeanUtils.copyProperties(postAddRequest, post);
        //获取当前用户
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());
        //post内tag为json，而postService.saveOrUpdate()方法要求tag为List<String>
        post.setTags(JSONUtil.toJsonPrettyStr(postAddRequest.getTags()));
        //设置post的收藏点赞
        post.setFavourNum(0);
        post.setThumbNum(0);
        post.setCommentNum(0);
        boolean save = postService.saveOrUpdate(post);
        ThrowUtils.throwIf( !save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(post.getId());
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation( value = "删除帖子")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody PostDeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        postService.delete( deleteRequest, request);
        return ResultUtils.success(true);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postUpdateRequest
     * @return
     */
    @ApiOperation( value = "更新帖子(管)")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException( ErrorCode.PARAMS_ERROR);
        }
        Long id = postUpdateRequest.getId();
        String title = postUpdateRequest.getTitle();
        String content = postUpdateRequest.getContent();
        List<String> tags = postUpdateRequest.getTags();
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf( oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        oldPost.setTitle(title);
        oldPost.setContent(content);
        oldPost.setTags(JSONUtil.toJsonStr(tags));
        boolean result = postService.saveOrUpdate(oldPost);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @ApiOperation( value = "根据id获取帖子")
    @GetMapping("/get/vo")
    public BaseResponse<PostVO> getPostVOById(long id, HttpServletRequest request) {
        Post post = postService.getById(id);
        PostVO postVO = postService.getPostVO(post);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        List<PostComment> postCommentList = postCommentService.list(new QueryWrapper<PostComment>().eq("postId", id));
        postVO.setPostCommentList(postCommentList);
        return ResultUtils.success(postVO);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param postQueryRequest
     * @return
     */
    @ApiOperation( value = "分页获取列表(管)")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Post>> listPostByPage(@RequestBody PostQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @ApiOperation("分页获取帖子列表（封装类）")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                       HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success( postService.getPostVOPage(postPage,request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "分页获取当前用户创建的资源列表")
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostVO>> listMyPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                         HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(loginUser.getId());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success( postService.getPostVOPage(postPage,request));
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param postEditRequest
     * @param request
     * @return
     */
    @ApiOperation( value = "更新帖子")
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody PostEditRequest postEditRequest, HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postEditRequest, post);
        return ResultUtils.success(postService.updateById(post));
    }


}
